package admin.data;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import models.EmailStatisticModel;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyOpts;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public class EmailStatisticData {
	private Objectify ofy;

	private Cache cache = null;

	private String prefix = "emailStatisticData_";

	private int limit = 20;

	private int page = 1;

	public int getLimit() {
		return limit;
	}

	public void setLimit(int limit) {
		this.limit = limit;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public EmailStatisticData() {
		try {
			ObjectifyService.register(EmailStatisticModel.class);
		} catch (Exception e) {
			// e.printStackTrace();
		}

		try {
			cache = CacheManager.getInstance().getCacheFactory()
					.createCache(Collections.emptyMap());
		} catch (CacheException e) {
			// e.printStackTrace();
		}

		ObjectifyOpts opts = new ObjectifyOpts().setSessionCache(true);
		ofy = ObjectifyService.begin(opts);
	}

	@SuppressWarnings("unchecked")
	public void insert(EmailStatisticModel statistic) {
		if (cache != null) {
			cache.put(prefix + statistic.getDoc(), statistic);
		}

		ofy.put(statistic);
	}

	@SuppressWarnings("unchecked")
	public EmailStatisticModel getStatisticByDateString(String doc) {
		EmailStatisticModel statistic = new EmailStatisticModel();
		if (cache != null && cache.containsKey(prefix + doc)) {
			statistic = (EmailStatisticModel) cache.get(prefix + doc);
		} else {
			try {
				statistic = ofy.get(new Key<EmailStatisticModel>(
						EmailStatisticModel.class, doc));
				cache.put(prefix + doc, statistic);
			} catch (Exception e) {
				statistic = null;
			}
		}
		return statistic;
	}

	public List<EmailStatisticModel> getStatisticByDate(Date fromDate,
			Date toDate) {
		List<EmailStatisticModel> list = new ArrayList<EmailStatisticModel>();

		Calendar to = Calendar.getInstance();
		if (toDate != null) {
			to.setTime(toDate);
		}
		to.set(Calendar.DATE, to.get(Calendar.DATE) + 1);
		int start = (page - 1) * limit;
		Query<EmailStatisticModel> q = ofy.query(EmailStatisticModel.class)
				.filter("dateOfCreate >=", fromDate)
				.filter("dateOfCreate <=", to.getTime()).limit(limit).offset(start);
		for (EmailStatisticModel statistic : q) {
			list.add(statistic);
		}
		return list;
	}

}
